# -*- coding:UTF-8 -*-
import logging
from flask import render_template
from datetime import timedelta
from functools import wraps
from flask import session, Response, url_for, request, redirect
from urllib.parse import quote
from src.common import JSON, filters
from src.jsapi import JSApi

logger = logging.getLogger("cqzl")

__author__ = 'raptor'

__doc__ = """
"""


def init(app):
    from src.webapi import index, page
    # 过期时间,通过cookie实现的
    app.permanent_session_lifetime = timedelta(days=30)
    app.register_blueprint(index.bp, url_prefix="/reservation/api")
    app.register_blueprint(page.bp, url_prefix="/reservation")

    filters.init(app)


def token_required(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        # 设为True时仅供测试之用
        if False:
            return func(*args, **kwargs)
        api = JSApi(session)

        if request.args.get("access_token"):
            if not request.args.get("user_id") or request.args.get("user_id") == 'undefined':
                return render_template("error/error.html", errmsg="请到微信公众号中绑定用户信息", code=500), 500
            if not api.access_token or (api.access_token and api.access_token != request.args.get("access_token")):
                # check Token
                api.access_token = request.args.get("access_token")
                isAuth = api.check_token()
                if isAuth:
                    session["access_token"] = api.access_token
                else:
                    return render_template("error/error.html", errmsg="没有权限", code=500), 500
        if request.args.get("openid"):
            if not api.openid or (api.openid and api.openid != request.args.get("openid")):
                api.openid = request.args.get("openid")
                session["openid"] = api.openid
        if request.args.get("user_id"):
            if not api.user_id or (api.user_id and api.user_id != request.args.get("user_id")):
                api.user_id = request.args.get("user_id")
                session["user_id"] = api.user_id
        if api.user_id:
            kwargs['jsapi'] = api
        else:
            return render_template("error/error.html", errmsg="请到微信公众号中绑定用户信息", code=500), 500
        try:
            return func(*args, **kwargs)
        except Exception as e:
            from traceback import format_exc
            logger.error(format_exc())
            return render_template("error/error.html", errmsg="系统错误，详见日志", code=500), 500
        return render_template("error/error.html", errmsg="系统错误，详见日志", code=500), 500

    return wrapper


def json_return(status, result):
    if status and status == 200:
        return JSON.dumps(dict(code=status, data=result))
    else:
        return JSON.dumps(dict(code=status, errmsg=result))
